package pl.streamsoft.currencyApp.services;

import java.util.List;

import pl.streamsoft.currencyApp.model.Currency;
import pl.streamsoft.currencyApp.parser.ICurrencyParser;
import pl.streamsoft.currencyApp.stream.IStream;

public class CurrencyService implements ICurrencyService {
	
	private IStream urlStream;
	private ICurrencyParser xmlParser;
	private List<Currency> listOfCurrencies;
	
	public CurrencyService(IStream stream, ICurrencyParser parser) {
		this.urlStream = stream;
		this.xmlParser = parser;
		getListOfCurrenciesFromURL();
	}

	@Override
	public Currency getCurrencyByCode(String codeName) {
		if(!listOfCurrencies.isEmpty()){
			for(Currency el: listOfCurrencies){
				if(el.getCurrencyCode().equals(codeName))
					return el;
			}
		}
		
		return null;
	}

	@Override
	public Currency getCurrencyByName(String name) {
		if(!listOfCurrencies.isEmpty()){
			for(Currency el: listOfCurrencies){
				if(el.getName().equals(name))
					return el;
			}
		}
		
		return null;
	}
	
	@Override
	public List<Currency> getListOfCurrencies() {
		return listOfCurrencies;
	}
	
	private List<Currency> getListOfCurrenciesFromURL() {
		List<Currency> list = this.xmlParser.getListOfCurrenciesFromStringFile(this.urlStream.getFile());
		this.listOfCurrencies = list;
		return listOfCurrencies;
	}
}
